<script setup lang="ts">
import { computed, ref, watch, h } from 'vue'
import { Segmented, Input, Popover, Button, message, notification } from 'ant-design-vue'
import { useDocumentVisibility } from '@vueuse/core'
import { useTimer } from '@/page/main/useTimer.ts'
import { SmileOutlined } from '@ant-design/icons-vue'
import { getDiffDataByTime } from '@/page/main/getDiff.ts'
import RenderContent from '@/page/main/RenderContent.vue'

const getServerData = () => {
  return fetch('/serverData.json')
    .then((res) => res.json())
    .then((res) => res.filter((i) => i.dir !== 'assets'))
}
const serverData = ref([])

// 分段器
const value = ref('最新上传')
const search = ref('')
const options = computed(() => {
  return ['最新上传', '全部', '最近使用', ...new Set(serverData.value.map((item) => item.type))].filter(
    (i) => i,
  )
})

getServerData().then((res) => {
  serverData.value = res
})

const serverDataFilter = computed(() => {
  let data = []
  if (value.value === '全部') {
    data = serverData.value
  } else if (value.value === '最新上传') {
    const _data = [...serverData.value]
    _data.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime() )
    data = _data.slice(0,10)
  } else if (value.value === '最近使用') {
    recentData.value.forEach((item) => {
      const find = serverData.value.find((i) => i.time === item)
      if (find) {
        data.push(find)
      }
    })
  } else {
    data = serverData.value.filter((i) => i.type === value.value)
  }
  data = data.filter((i) => {
    if (search.value) {
      return i.dir.includes(search.value)
    } else {
      return true
    }
  })
  return data
})

const getRecentData = () => {
  const recentString = localStorage.getItem('recent') || ''
  return recentString ? JSON.parse(recentString) : []
}

const setRecentData = (data) => {
  localStorage.setItem('recent', JSON.stringify(data))
}

const recentData = ref(getRecentData())
const setRecent = (item) => {
  let localData = getRecentData()
  // 先删除
  localData = localData.filter((i) => i !== item.time)
  localData.unshift(item.time)
  setRecentData(localData)
  // recentData.value = getRecentData()

  // location.replace(item.dir)
}
function copyText(value) {
  if (navigator.clipboard) {
    return navigator.clipboard.writeText(value)
  } else {
    const tempInput = document.createElement('input')
    document.body.appendChild(tempInput)
    tempInput.value = value
    tempInput.select()
    document.execCommand('Copy')
    document.body.removeChild(tempInput)
    return Promise.resolve()
  }
}
const copyName = (dir) => {
  copyText(dir)
  message.success(`已复制 [ ${dir} ] 到粘贴板`)
}

// 实时更新

const visibility = useDocumentVisibility()

let lastData = null
const checkUpdate = async () => {
  console.log('checkUpdate ... ')
  const newData = await getServerData()
  const currentData = JSON.stringify(newData)

  if (lastData && currentData !== lastData) {
    // 执行更新及提醒
    const diffData = getDiffDataByTime(newData, serverData.value)

    const list = []

    list.push(
      ...diffData.added.map((i) => {
        return {
          ...i,
          status: 'added',
        }
      }),
    )
    list.push(
      ...diffData.deleted.map((i) => {
        return {
          ...i,
          status: 'deleted',
        }
      }),
    )
    const key = `open${Date.now()}`
    notification.open({
      message: '内容更新提醒',
      description: () => h(RenderContent, { list }),
      duration: 10,
      btn: () =>
        h(
          Button,
          {
            type: 'primary',
            size: 'small',
            onClick: () => notification.close(key),
          },
          { default: () => '我知道了' },
        ),
      key,
      icon: () => h(SmileOutlined, { style: 'color: #108ee9' }),
    })

    serverData.value = newData
  }

  lastData = currentData
}

const { startTimer, stopTimer } = useTimer(checkUpdate, 5000)
startTimer()
watch(visibility, (value) => {
  if (value === 'visible') {
    checkUpdate()
    startTimer()
  }
  if (value === 'hidden') {
    stopTimer()
  }
})

// 标题
const updateTitle = () => {
  fetch('/projectTitle.txt')
    .then((res) => res.text())
    .then((title) => {
      document.title = title
    })
}
updateTitle()
</script>

<template>
  <div class="main">
    <div class="z-flex-row filter">
      <div class="z-flex1">
        <Segmented v-model:value="value" :options="options" v-if="options.length" />
      </div>
      <div>
        <Input v-model:value="search" placeholder="搜索" />
      </div>
    </div>

    <div class="item" v-for="item in serverDataFilter">
      <a
        class="item-inner z-flex-row z-items-center g-transition"
        :href="item.dir"
        @click="setRecent(item)"
      >
        <div
          class="cover z-background-cover-image"
          :style="{ 'background-image': `url('${item.cover}')` }"
          v-if="item.cover"
        ></div>
        <div v-else class="cover z-background-cover-image cover-default"></div>
        <Popover placement="rightTop" v-if="item.cover">
          <template #content>
            <img class="cover-hover g-transition" :src="item.cover" alt="封面" />
          </template>
          <template #title>
            <span>{{ item.dir }}</span>
          </template>
          <div class="dir">{{ item.dir }}</div>
        </Popover>
        <div class="dir" v-else>{{ item.dir }}</div>
        <!--<div class="cover z-background-cover-image" style="background-image: url(https://gaoding-market.dancf.com/market-operations/market/side/9662df03c9c94441acc2fefda6acb477/1759980489489.jpg?x-oss-process=image/resize,w_260/sharpen,80/interlace,1,image/format,webp)"></div>-->

        <div class="time z-flex1">{{ item.time }}</div>
        <Button class="copy-name" @click.stop.prevent="copyName(item.dir)">复制名称</Button>
      </a>
    </div>
  </div>
</template>

<style scoped>
.main {
  padding: 20px;
  width: 1200px;
  max-width: 70%;
  margin: 0 auto;
}
.filter {
  padding: 10px 0;
  position: sticky;
  top: 0;
  background-color: white;
  z-index: 1;
}
.cover {
  height: 40px;
  border: 1px solid #e6e6e6;
  aspect-ratio: 16/9;
  border-radius: 5px;
  position: relative;
}

.cover-default {
  background-size: 26px;
  background-image: url('@/assets/dir.svg');
}
.cover-hover {
  background-color: #f3f3f3;
  height: 208px;
  aspect-ratio: 16/9;
  border-radius: 10px;
}

.time {
  color: darkgray;
  text-align: right;
}
.item {
  padding: 5px 0;
}
.item-inner {
  border: 1px solid #e6e6e6;
  border-radius: 10px;
  padding: 10px;
  text-decoration: none;
  cursor: pointer;
}
.item-inner:hover {
  background-color: #f3f3f3;
}
.dir,
.copy-name {
  margin-left: 10px;
}
.time {
}

:deep(.ant-segmented .ant-segmented-item-label) {
  padding: 0 20px;
}
</style>
